import {routerRedux} from 'dva/router';
import pathToRegexp from 'path-to-regexp'
import api from '../api';
import moment from 'moment'

export default {
  namespace : 'dailysummaryTarget',
  state : {
    data:[],//每次请求的数据的合集,有key、data、status
  },
  subscriptions : {
    setup({dispatch, history}) {
      history.listen(({pathname,query}) => {
        if( pathname === '/tradeAnalysis/tca/dailySummaryTarget' ){
          const {from,...newQuery}=query
          if(from){
            dispatch({
              type:'changeRouter',
              payload:{
                pathname,
                query:newQuery
              }
            })
          }else{
            dispatch({
              type: 'whetherRequest',
              payload:query
            })
          }
        }
      })
    }
  },
  effects : {
    // 判断是否需要查询结果
    * whetherRequest({payload}, {call, put,select}) {
      const state=yield select(state => state.dailysummaryTarget)
      const atData=state.data.find(item=>item.key===payload.at)
      // 是否是第一次请求
      if(!atData){
        // 是的话，正常请求
        yield put({
          type:'requestResult',
          payload
        })
      }else{
        // 不是的话，看本次的参数和上次的参数是否一致：
        // 一致的话，不请求，不一致的话，正常请求
        // 定义一个对象用于定义参数

        const newObj={}
        for(var key in payload){
          if(key!='at'){
            newObj[key]=atData.data[key]
          }else{
            newObj[key]=atData.key
          }
        }
        if(JSON.stringify(payload)!=JSON.stringify(newObj)){
          yield put({
            type:'requestResult',
            payload
          })
        }
      }
    },
    // 查询结果
    * requestResult({payload}, {call, put,select}){
      const response = yield call(api.tca.getDailysummaryTarget, payload);
      yield put({type: 'querySuccess', payload: {
        key:payload.at,
        data:response.data
      }});
    },
    // 改变路由
    * changeRouter({payload}, {put}){
      yield put(routerRedux.push(payload))
    }
  },
  reducers : {
    querySuccess(state, {payload}) {
      const keyIndex=state.data.findIndex((item, index, arr)=>item.key===payload.key)
      if(keyIndex>-1){
        state.data.splice(keyIndex,1,payload)
      }else{
        state.data.push(payload)
      }

      return {
        ...state
      }
    }
  }
};
